<?php

namespace app\admin\controller;

use GuzzleHttp;

/**
 * Qbittorrent Api 实现
 * @class Qbapi
 * @package app\admin\controller
 */
class Qbapi
{
    /**
     * 接口后缀地址
     * @var string
     */
    private $api_prefix = [
        'login' => '/api/v2/auth/login', // 登录接口
        'logout' => '/api/v2/auth/logout', // 登录接口
        'torrentsInfo' => '/api/v2/torrents/info', //获取所有种子列表
        'torrentAdd' => '/api/v2/torrents/add', // 添加新种子
    ];
    /**
     * 接口前缀地址
     */
    private $base_url;
    /**
     * 接口认证session_id
     */
    private $session_id;
    /**
     * 配置参数
     */
    private $config;
    /**
     * guzzle的请求对象
     */
    private $client;
    /**
     * login状态
     */
    public $login_status;

    /**
     * 构造函数
     * @param array $config
     */
    public function __construct($config = [])
    { // config设置全局化
        $this->config = $config;
        // 设置初始接口地址
        $this->base_url = $this->config['port'] ? $this->config['host'] . ':' . $this->config['port'] . '/' : $this->config['host'] . '/';
        // guzzle client对象默认初始化设置
        $this->client = new GuzzleHttp\Client(['base_uri' => $this->base_url, ['verify' => false, 'timeout' => 10]]);
        $this->login();
    }
    public function login()
    {
        try {
            $response = $this->client->post($this->api_prefix['login'], [
                'form_params' => [
                    'username' => $this->config['username'],
                    'password' => $this->config['password'],
                ],
            ]);
            $headers = $response->getHeaders();
            if ($response->getReasonPhrase() == 'OK') {
                preg_match('/SID=(\S[^;]+)/', $headers['set-cookie'][0], $matches);
                $this->session_id = $matches[1];
                $jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
                    [
                        'SID' => $this->session_id,
                    ],
                    parse_url($this->config['host'])['host']
                );
                // 将 Cookie 添加到默认请求头部
                $this->client = new GuzzleHttp\Client([
                    'base_uri' => $this->base_url,
                    'verify' => false,
                    'timeout' => 10,
                    'cookies' => $jar,
                ]);
                $this->login_status = 1;
                return json(['code'=>1,'msg'=>"Qb 登录成功"]);
            } else {
                $this->login_status = 0;
                return json(['code'=>0,'msg'=>"Qb 登录失败,请检查账号密码是否正确"]);
            }
        } catch (\Exception $e) {
            $this->login_status = 0;
            return json(['code'=>0,'msg'=>"密码错误次数过多，账号已被封禁，请重启qb容器"]);
        }
    }

    public function logout()
    {
        $response = $this->client->get($this->api_prefix['logout']);
        $this->session_id = null;
        return "Qb 登出成功";
    }

    public function getTorrentsInfo($hash = '',$filter ='')
    {
        $response = $this->client->post($this->api_prefix['torrentsInfo'],[
          'form_params' => [
            'hashes' => $hash,
            'filter' => $filter
          ]
        ]);
        return json_decode($response->getBody()->getContents(),true);
    }
    public function addTorrent($url,$save_path,$is_skip_checking, $is_paused, $upLimit = 0,$dlLimit = 0)
    {
        $is_skip_checking == 1 ? $is_skip_checking = 'true' : $is_skip_checking = 'false';
        $is_paused == 1 ? $is_paused = 'false' : $is_paused = 'true';
        $response = $this->client->post($this->api_prefix['torrentAdd'], [
            'form_params' => [
                'urls'=>$url,
                "savepath" => $save_path,
                'skip_checking' => $is_skip_checking,
                'paused' => $is_paused,
                'tags'=> "Reseed Puppy",
                "upLimit"=>$upLimit * 1024,
                "dlLimit"=>$dlLimit * 1024,
            ],
        ]);
        return $response->getBody()->getContents();
    }
}
